// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview For use as a Google Apps Script.  Reads Inputs and
 * Templates from two sheets and runs each input through each
 * template.  Inserts a new sheet to display generated output.
 * Also makes a call to tracking url (if provided) to track
 * script usage.
 */

goog.provide('ads_mult');

goog.require('ads_mult.Processor');
goog.require('ads_mult.SpreadsheetReader');
goog.require('ads_mult.SpreadsheetWriter');

goog.require('ads_mult.common');

/**
 * Process the templates and variables and write out an output sheet.
 * @private
 */
ads_mult.run_ = function() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();

  var ssReader = new ads_mult.SpreadsheetReader(ss);
  var inputObjects = ssReader.getInputs('Inputs');
  var templateObjects = ssReader.getTemplates('Templates');

  var limits = ssReader.getLimits('Character Limits');
  var headers = ssReader.getHeaders('Templates');

  var processor = new ads_mult.Processor(inputObjects, templateObjects);
  var outputObjects = processor.process();

  var ssWriter = new ads_mult.SpreadsheetWriter(ss);
  ssWriter.writeOutputs('Outputs', headers, outputObjects, limits);

  // prep for usage tracking
  var normHeaders = ads_mult.common.normalizeHeaders(headers);
  var ldap = Session.getUser().getUserLoginId();
  // count the number of creatives generated
  var n_creatives = outputObjects.length;
  // assume first column contains campaign name
  var n_campaigns = ads_mult.common.countUniqueInColumn(outputObjects,
                                                        normHeaders[0]);
  // and get those campaign names
  var campaigns = ads_mult.common.getUniqueInColumn(outputObjects, normHeaders[0]);
  // assume second column contains ad group name
  var n_ad_groups = ads_mult.common.countUniqueInColumn(outputObjects,
                                                        normHeaders[1]);
};

/**
 * Sends usage information to external app.
 * @param {string} url url to make call to.
 * @param {string} cid customer id for the generated campaigns.
 * @param {string} ldap LDAP of user who is generating creatives.
 * @param {number} num_creatives the number of creatives generated.
 * @param {number} num_campaigns the number of unique campaigns.
 * @param {number} num_ad_groups the number of unique ad groups.
 * @param {Array.<string>} campaigns a list of campaign names.
 * @param {string} version version of the Ads Multiplier.
 * @private
 */
ads_mult.trackUsage_ = function(url, cid, ldap, num_creatives, num_campaigns,
                           num_ad_groups, campaigns, version) {
  var params = [];
  params.push('cid=' + cid);
  params.push('version=' + version);
  params.push('ldap=' + ldap);
  params.push('n_creatives=' + parseInt(num_creatives, 10));
  params.push('n_campaigns=' + parseInt(num_campaigns, 10));
  params.push('n_ad_groups=' + parseInt(num_ad_groups, 10));
  for (var i = 0, camp; camp = campaigns[i]; i++) {
    params.push('campaigns=' + encodeURIComponent(camp));
  }

  var advancedArgs = {
    method: 'post',
    contentType: 'application/x-www-form-urlencoded;charset=utf-8',
    payload: params.join('&')
  };
  try {
    UrlFetchApp.fetch(url, advancedArgs);
  } catch (err) {
    // just fail silently
  }
};

/**
 * Creates a new menu with an option to generate the output and a link to the
 * FAQ.
 * @private
 */
ads_mult.createMenus_ = function() {
  var activeSheet = SpreadsheetApp.getActiveSpreadsheet();
  var generateMenuItem = {
    'name': 'Generate Output',
    'functionName': 'generateOutput'
  };
  var faqMenuItem = {
    'name': 'FAQ',
    'functionName': 'showFaq'
  };
  var menuEntries = [generateMenuItem, faqMenuItem];
  activeSheet.addMenu('Ads Multiplier', menuEntries);
};


/**
 * Display's the tool's FAQ.
 * @private
 */
ads_mult.showFaq_ = function() {
  Browser.msgBox('For frequently asked questions about this tool, please ' +
                 'visit wiki at http://code.google.com/p/google-ads-multiplier');
};


/**
 * Called by the Google Apps Script when the spreadsheet first opens.
 * @export
 */
function onOpen() {
  ads_mult.createMenus_();
}


/**
 * Shows the tool's FAQ.
 * @export
 */
function showFaq() {
  ads_mult.showFaq_();
}


/**
 * Starts the output generation.
 * @export
 */
function generateOutput() {
  ads_mult.run_();
}
